package com.tanhua.bg.service;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.Month;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.bg.enums.AreaEnum;
import com.tanhua.bg.enums.IndustryEnum;
import com.tanhua.bg.enums.MonthEnum;
import com.tanhua.bg.pojo.Amount;
import com.tanhua.bg.vo.CompareResult;
import com.tanhua.bg.vo.DashResult;

import com.tanhua.bg.pojo.Log;
import com.tanhua.bg.vo.TotalDataVo;
import com.tanhua.common.enums.SexEnum;
import com.tanhua.common.mapper.UserInfoMapper1;
import com.tanhua.common.pojo.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class DashboardService {

    @Autowired
    private UserInfoMapper1 userInfoMapper;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private MongoService mongoService;

    public DashResult distribution(Date startTime, Date endTime) {

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.ge("created",startTime);
        queryWrapper.lt("created",endTime);
        List<UserInfo> list = userInfoMapper.selectList(queryWrapper);

        Amount[] industryDistribution = this.totalIndustryAmount(list);
        Amount[] ageDistribution = this.totalAgeAmount(list);
        Amount[] genderDistribution = this.totalGenderDistribution(list);
        Amount[] localDistribution = this.totalLocalDistribution(list);
        Amount[] localTotal = this.totalLocalTotal(list);

        DashResult dashResult = new DashResult();
        dashResult.setIndustryDistribution(industryDistribution);
        dashResult.setAgeDistribution(ageDistribution);
        dashResult.setGenderDistribution(genderDistribution);
        dashResult.setLocalDistribution(localDistribution);
        dashResult.setLocalTotal(localTotal);
        return dashResult;
    }

    private Amount[] totalLocalTotal(List<UserInfo> list) {
        Integer huazhong = 0;
        Integer huabei = 0;
        Integer huadong = 0;
        Integer huanan = 0;
        Integer xibei = 0;
        Integer dongbei = 0;
        Integer xinan = 0;

        for (UserInfo userInfo : list) {
            String province = userInfo.getCity().split("-")[0];
            String area = AreaEnum.getAreaByProvince(province);
            if (StrUtil.equals(area,"华中地区")){
                huazhong++;
            }else if(StrUtil.equals(area,"华北地区")){
                huabei++;
            }else if(StrUtil.equals(area,"华东地区")){
                huadong++;
            }else if(StrUtil.equals(area,"华南地区")){
                huanan++;
            }else if(StrUtil.equals(area,"西北地区")){
                xibei++;
            }else if(StrUtil.equals(area,"东北地区")){
                dongbei++;
            }else if(StrUtil.equals(area,"西南地区")){
                xinan++;
            }
        }
        Amount amount1 = new Amount("华中地区",huazhong);
        Amount amount2 = new Amount("华北地区",huabei);
        Amount amount3 = new Amount("华东地区",huadong);
        Amount amount4 = new Amount("华南地区",huanan);
        Amount amount5 = new Amount("西北地区",xibei);
        Amount amount6 = new Amount("东北地区",dongbei);
        Amount amount7 = new Amount("西南地区",xinan);

        Amount[] localTotal = {amount1,amount2,amount3,amount4,amount5,amount6,amount7};
        return localTotal;
    }

    private Amount[] totalLocalDistribution(List<UserInfo> list) {
        //华中
        Integer hubei = 0;
        Integer hunan = 0;
        Integer henan = 0;
        //华北
        Integer shanxi = 0;
        Integer hebei = 0;
        Integer beijing = 0;
        Integer tianjin = 0;
        Integer neimenggu = 0;
        //华东
        Integer zhejiang = 0;
        Integer anhui = 0;
        Integer shanghai = 0;
        Integer jiangxi = 0;
        Integer shandong = 0;
        Integer jiangsu = 0;
        Integer fujian = 0;
        Integer taiwan = 0;
        //华南
        Integer guangxi = 0;
        Integer guangdong = 0;
        Integer hainan = 0;
        Integer hongkong = 0;
        Integer macao = 0;
        //西北
        Integer qinghai = 0;
        Integer ningxia = 0;
        Integer shanxi2 = 0;
        Integer gansu = 0;
        Integer xinjiang = 0;
        //东北
        Integer jilin = 0;
        Integer heilongjiang = 0;
        Integer liaoning = 0;
        //西南
        Integer guizhou = 0;
        Integer yunnan = 0;
        Integer chongqing = 0;
        Integer sichuan = 0;
        Integer tibet = 0;
        for (UserInfo userInfo : list) {
            String province = userInfo.getCity().split("-")[0];
            if (StrUtil.equals(province,"湖北")){
                hubei++;
            }else if(StrUtil.equals(province,"湖南")){
                hunan++;
            }else if(StrUtil.equals(province,"河南")){
                henan++;
            }else if(StrUtil.equals(province,"山西")){
                shanxi++;
            }else if(StrUtil.equals(province,"河北")){
                hebei++;
            }else if(StrUtil.equals(province,"北京")){
                beijing++;
            }else if(StrUtil.equals(province,"天津")){
                tianjin++;
            }else if(StrUtil.equals(province,"内蒙古")){
                neimenggu++;
            }else if(StrUtil.equals(province,"台湾")){
                taiwan++;
            }else if(StrUtil.equals(province,"浙江")){
                zhejiang++;
            }else if(StrUtil.equals(province,"安徽")){
                anhui++;
            }else if(StrUtil.equals(province,"上海")){
                shanghai++;
            }else if(StrUtil.equals(province,"江西")){
                jiangxi++;
            }else if(StrUtil.equals(province,"山东")){
                shandong++;
            }else if(StrUtil.equals(province,"江苏")){
                jiangsu++;
            }else if(StrUtil.equals(province,"福建")){
                fujian++;
            }else if(StrUtil.equals(province,"广西")){
                guangxi++;
            }else if(StrUtil.equals(province,"广东")){
                guangdong++;
            }else if(StrUtil.equals(province,"海南")){
                hainan++;
            }else if(StrUtil.equals(province,"香港")){
                hongkong++;
            }else if(StrUtil.equals(province,"澳门")){
                macao++;
            }else if(StrUtil.equals(province,"青海")){
                qinghai++;
            }else if(StrUtil.equals(province,"宁夏")){
                ningxia++;
            }else if(StrUtil.equals(province,"陕西")){
                shanxi2++;
            }else if(StrUtil.equals(province,"甘肃")){
                gansu++;
            }else if(StrUtil.equals(province,"新疆")){
                xinjiang++;
            }else if(StrUtil.equals(province,"吉林")){
                jilin++;
            }else if(StrUtil.equals(province,"黑龙江")){
                heilongjiang++;
            }else if(StrUtil.equals(province,"辽宁")){
                liaoning++;
            }else if(StrUtil.equals(province,"贵州")){
                guizhou++;
            }else if(StrUtil.equals(province,"云南")){
                yunnan++;
            }else if(StrUtil.equals(province,"重庆")){
                chongqing++;
            }else if(StrUtil.equals(province,"四川")){
                sichuan++;
            }else if(StrUtil.equals(province,"西藏")){
                tibet++;
            }
        }
        Amount amount1 = new Amount("湖北", hebei);
        Amount amount2 = new Amount("湖南", hunan);
        Amount amount3 = new Amount("河南", henan);

        Amount amount4 = new Amount("山西", shanxi);
        Amount amount5 = new Amount("河北", hebei);
        Amount amount6 = new Amount("北京", beijing);
        Amount amount7 = new Amount("天津", tianjin);
        Amount amount8 = new Amount("内蒙古", neimenggu);

        Amount amount9 = new Amount("浙江", zhejiang);
        Amount amount10 = new Amount("安徽", anhui);
        Amount amount11= new Amount("上海", shanghai);
        Amount amount12= new Amount("江西", jiangxi);
        Amount amount13= new Amount("山东", shandong);
        Amount amount14= new Amount("江苏", jiangsu);
        Amount amount15= new Amount("福建", fujian);
        Amount amount16= new Amount("台湾", taiwan);

        Amount amount17= new Amount("广西", guangxi);
        Amount amount18= new Amount("广东", guangdong);
        Amount amount19= new Amount("海南", hainan);
        Amount amount20= new Amount("香港", hongkong);
        Amount amount21= new Amount("澳门", macao);

        Amount amount22= new Amount("青海", qinghai);
        Amount amount23= new Amount("宁夏", ningxia);
        Amount amount24= new Amount("陕西", shanxi2);
        Amount amount25= new Amount("甘肃", gansu);
        Amount amount26= new Amount("新疆", xinjiang);

        Amount amount27= new Amount("吉林", jilin);
        Amount amount28= new Amount("黑龙江", heilongjiang);
        Amount amount29= new Amount("辽宁", liaoning);

        Amount amount30= new Amount("贵州", guizhou);
        Amount amount31= new Amount("云南", yunnan);
        Amount amount32= new Amount("重庆", chongqing);
        Amount amount33= new Amount("四川", sichuan);
        Amount amount34= new Amount("西藏", tibet);

        Amount[] localDistribution = {amount1,amount2,amount3,amount4,amount5,amount6,amount7,amount8,amount9,amount10,
                amount11,amount12,amount13,amount14,amount15,amount16,amount17,amount18,amount19,amount20,amount21,amount22
                ,amount23,amount24,amount25,amount26,amount27,amount28,amount29,amount30,amount31,amount32,amount33,amount34};

        return localDistribution;
    }

    private Amount[] totalGenderDistribution(List<UserInfo> list) {
        Integer manCount = 0;
        Integer womanCount = 0;
        for (UserInfo userInfo : list) {
            SexEnum sex = userInfo.getSex();
            if (ObjectUtil.equal(sex,SexEnum.MAN)){
                manCount++;
            }else if(ObjectUtil.equal(sex,SexEnum.WOMAN)){
                womanCount++;
            }
        }
        Amount amount1 = new Amount(SexEnum.MAN.toString(), manCount);
        Amount amount2 = new Amount(SexEnum.WOMAN.toString(), womanCount);
        Amount[] genderDistribution = new Amount[2];
        genderDistribution[0] = amount1;
        genderDistribution[1] = amount2;
        return genderDistribution;
    }

    private Amount[] totalAgeAmount(List<UserInfo> list) {
        Integer underTwentyCount = 0;
        Integer twentyCount = 0;
        Integer thirtyCount = 0;
        Integer fortyCount = 0;
        Integer overFiftyCount = 0;
        for (UserInfo userInfo : list) {
            Integer age = userInfo.getAge();
            if (age<20){
                underTwentyCount++;
            }else if(age>=20&&age<30){
                twentyCount++;
            }else if(age>=30&&age<40){
                thirtyCount++;
            }else if(age>=40&&age<=50){
                fortyCount++;
            }else if(age>50){
                overFiftyCount++;
            }
        }
        Amount[] amounts = new Amount[5];
        Amount amount1 = new Amount("20以下",underTwentyCount);
        Amount amount2 = new Amount("20-29岁",twentyCount);
        Amount amount3 = new Amount("30-39岁",thirtyCount);
        Amount amount4 = new Amount("40-50岁",fortyCount);
        Amount amount5 = new Amount("50以上",overFiftyCount);
        amounts[0] = amount1;
        amounts[1] = amount2;
        amounts[2] = amount3;
        amounts[3] = amount4;
        amounts[4] = amount5;
        return amounts;
    }

    private Amount[] totalIndustryAmount(List<UserInfo> list) {
        Integer manufactureAmount = 0;  //制造业
        Integer serviceAmount = 0;      //服务业
        Integer landAmount = 0;         //地产
        Integer hotelsAmount = 0;       //住宿
        Integer eduAmount = 0;      //教育
        Integer caterAmount = 0;    //餐饮
        for (UserInfo userInfo : list) {
            String industry = userInfo.getIndustry();
           if (StrUtil.equals(industry, IndustryEnum.MANUFACTURE.toString())){
               manufactureAmount++;
           }else if(StrUtil.equals(industry,IndustryEnum.SERVICE.toString())){
                serviceAmount++;
           }else if(StrUtil.equals(industry,IndustryEnum.LANDED.toString())){
               landAmount++;
           }else if(StrUtil.equals(industry,IndustryEnum.HOTELS.toString())){
               hotelsAmount++;
           }else if(StrUtil.equals(industry,IndustryEnum.EDUCATION.toString())){
               eduAmount++;
           }else if(StrUtil.equals(industry,IndustryEnum.CATERING.toString())){
               caterAmount++;
           }
        }
        Amount manufacture = new Amount();
        manufacture.setTitle("制造");
        manufacture.setAmount(manufactureAmount);

        Amount service = new Amount();
        service.setTitle("服务");
        service.setAmount(serviceAmount);

        Amount land = new Amount();
        land.setTitle("地产");
        land.setAmount(landAmount);

        Amount hotels = new Amount();
        hotels.setTitle("住宿");
        hotels.setAmount(hotelsAmount);

        Amount edu = new Amount();
        edu.setTitle("服务");
        edu.setAmount(eduAmount);

        Amount cater = new Amount();
        cater.setTitle("餐饮");
        cater.setAmount(caterAmount);

        Amount[] industryDistribution = new Amount[6];
        industryDistribution[0] = manufacture;
        industryDistribution[1] = service;
        industryDistribution[2] = land;
        industryDistribution[3] = hotels;
        industryDistribution[4] = edu;
        industryDistribution[5] = cater;

        return industryDistribution;
    }

    public CompareResult queryUsersData(Date startTime, Date endTime, String type) {
        CompareResult compareResult = null;
        switch(type){
            case "101": {
                compareResult = queryUserInfoDate(startTime, endTime);
                break;
            }
            case "102": {
                compareResult = queryLogDate(startTime, endTime);
                break;
            }
            case "103": {
                compareResult = queryUserAndLogDate(startTime,endTime);
                break;
            }
        }
       if (ObjectUtil.isEmpty(compareResult)){
           return null;
       }
       return compareResult;
    }

    public List<UserInfo> queryUserInfoByTime(Date startTime, Date endTime){
        QueryWrapper<UserInfo> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.ge("created",startTime);
        queryWrapper1.lt("created",endTime);
        List<UserInfo> userInfoList = userInfoMapper.selectList(queryWrapper1);
        return userInfoList;
    }

    public List<Log> queryLogsByTime(Date startTime, Date endTime){
        Query query = Query.query(Criteria.where("created").gte(startTime)
                .andOperator(Criteria.where("created").lt(endTime)));
//        List<Log> logs = mongoTemplate.find(query, Log.class);
        return mongoTemplate.find(query, Log.class);
    }

    private CompareResult queryUserAndLogDate(Date startTime, Date endTime) {
        //今年
        List<UserInfo> userInfoList = queryUserInfoByTime(startTime, endTime);
        List<Log> logs = queryLogsByTime(startTime, endTime);
        Amount[] thisYear = totalSurvivor(userInfoList, logs);

        DateTime startTimeLastYear = DateUtil.offsetMonth(startTime, -12);
        DateTime endTimeLastYear = DateUtil.offsetMonth(endTime, -12);
        List<UserInfo> userInfoList2 = queryUserInfoByTime(startTimeLastYear, endTimeLastYear);
        List<Log> logs2 = queryLogsByTime(startTimeLastYear, endTimeLastYear);
        Amount[] lastYear = totalSurvivor(userInfoList2, logs2);

        CompareResult compareResult = new CompareResult();
        compareResult.setThisYear(thisYear);
        compareResult.setLastYear(lastYear);
        return compareResult;
    }

    private Amount[] totalSurvivor(List<UserInfo> userInfoList,List<Log> logs){
        Integer Jan = 0;
        Integer Feb = 0;
        Integer Mar = 0;
        Integer Apr = 0;
        Integer May = 0;
        Integer Jun = 0;
        Integer Jul = 0;
        Integer Aug = 0;
        Integer Sept = 0;
        Integer Oct = 0;
        Integer Nov = 0;
        Integer Dec = 0;
        for (UserInfo userInfo : userInfoList) {
            Date firstDay = userInfo.getCreated();
            DateTime dateTime = DateUtil.offsetDay(firstDay, 1);
            for (Log log : logs) {
                Long logTime = log.getLogTime();
                if (ObjectUtil.equal(userInfo.getUserId(),log.getUserId())
                        &&logTime>=(DateUtil.beginOfDay(Convert.toDate(dateTime)).getTime())
                        &&logTime<=(DateUtil.endOfDay(Convert.toDate(dateTime)).getTime())){
                    Month month = DateUtil.monthEnum(new Date(logTime));
                    switch (month.getValue()){
                        case 0:
                            Jan++;
                            break;
                        case 1:
                            Feb++;
                            break;
                        case 2:
                            Mar++;
                            break;
                        case 3:
                            Apr++;
                            break;
                        case 4:
                            May++;
                            break;
                        case 5:
                            Jun++;
                            break;
                        case 6:
                            Jul++;
                            break;
                        case 7:
                            Aug++;
                            break;
                        case 8:
                            Sept++;
                            break;
                        case 9:
                            Oct++;
                            break;
                        case 10:
                            Nov++;
                            break;
                        case 11:
                            Dec++;
                            break;
                    }
                }
            }
        }

        Amount amount1 = new Amount(MonthEnum.JAN.toString(), Jan);
        Amount amount2 = new Amount(MonthEnum.FEB.toString(), Feb);
        Amount amount3 = new Amount(MonthEnum.MAR.toString(), Mar);
        Amount amount4 = new Amount(MonthEnum.APR.toString(), Apr);
        Amount amount5 = new Amount(MonthEnum.MAY.toString(), May);
        Amount amount6 = new Amount(MonthEnum.JUN.toString(), Jun);
        Amount amount7 = new Amount(MonthEnum.JUL.toString(), Jul);
        Amount amount8 = new Amount(MonthEnum.AUG.toString(), Aug);
        Amount amount9 = new Amount(MonthEnum.SEPT.toString(), Sept);
        Amount amount10 = new Amount(MonthEnum.OCT.toString(), Oct);
        Amount amount11 = new Amount(MonthEnum.NOV.toString(), Nov);
        Amount amount12 = new Amount(MonthEnum.DEC.toString(), Dec);
        Amount[] year = {amount1,amount2,amount3,amount4,amount5,amount6,amount7,amount8,amount9,amount10,amount11,amount12};
        return year;
    }


    private CompareResult queryLogDate(Date startTime, Date endTime) {
      /*  Query query = Query.query(Criteria.where("created").gte(startTime)
                .andOperator(Criteria.where("created").lt(endTime)));
        List<Log> logs = mongoTemplate.find(query, Log.class);*/
        List<Log> logs = queryLogsByTime(startTime, endTime);
        List<Log> logs2 = new ArrayList<>();
        if (CollUtil.isNotEmpty(logs)){
            for (Log log : logs) {
                if (!CollUtil.contains(logs2,log.getUserId())){
                    logs2.add(log);
                }
            }
        }

        Amount[] thisYear = this.totalAliveUserMonth(logs2);

        //查询去年同时期的活跃用户
        DateTime startTimeLastYear = DateUtil.offsetMonth(startTime, -12);
        DateTime endTimeLastYear = DateUtil.offsetMonth(endTime, -12);

        /*Query query2 = Query.query(Criteria.where("created").gte(startTimeLastYear)
                .andOperator(Criteria.where("created").lt(endTimeLastYear)));
        List<Log> logs3 = mongoTemplate.find(query2, Log.class);*/
        List<Log> logs3 = queryLogsByTime(startTimeLastYear, endTimeLastYear);
        List<Log> logs4 = new ArrayList<>();
        if (CollUtil.isNotEmpty(logs3)){
            for (Log log : logs3) {
                if (!CollUtil.contains(logs4,log.getUserId())){
                    logs4.add(log);
                }
            }
        }
        Amount[] lastYear = this.totalAliveUserMonth(logs4);
        CompareResult compareResult = new CompareResult();
        compareResult.setThisYear(thisYear);
        compareResult.setLastYear(lastYear);
        return compareResult;
    }

    private Amount[] totalAliveUserMonth(List<Log> logs2) {
        if (CollUtil.isEmpty(logs2)){
            return null;
        }
        Integer Jan = 0;
        Integer Feb = 0;
        Integer Mar = 0;
        Integer Apr = 0;
        Integer May = 0;
        Integer Jun = 0;
        Integer Jul = 0;
        Integer Aug = 0;
        Integer Sept = 0;
        Integer Oct = 0;
        Integer Nov = 0;
        Integer Dec = 0;

        for (Log log : logs2) {
            Long created = log.getCreated();
            Date date = new Date(created);
            int month = DateUtil.month(date);
//            Month month1 = DateUtil.monthEnum(created);
            if (month== MonthEnum.JAN.getValue()){
                Jan++;
            } else if (month==MonthEnum.FEB.getValue()) {
                Feb++;
            }else if (month==MonthEnum.MAR.getValue()) {
                Mar++;
            }else if (month==MonthEnum.APR.getValue()) {
                Apr++;
            }else if (month==MonthEnum.MAY.getValue()) {
                May++;
            }else if (month==MonthEnum.JUN.getValue()) {
                Jun++;
            }else if (month==MonthEnum.JUL.getValue()) {
                Jul++;
            }else if (month==MonthEnum.AUG.getValue()) {
                Aug++;
            }else if (month==MonthEnum.SEPT.getValue()) {
                Sept++;
            }else if (month==MonthEnum.OCT.getValue()) {
                Oct++;
            }else if (month==MonthEnum.NOV.getValue()) {
                Nov++;
            }else if (month==MonthEnum.DEC.getValue()) {
                Dec++;
            }
        }
        Amount amount1 = new Amount(MonthEnum.JAN.toString(), Jan);
        Amount amount2 = new Amount(MonthEnum.FEB.toString(), Feb);
        Amount amount3 = new Amount(MonthEnum.MAR.toString(), Mar);
        Amount amount4 = new Amount(MonthEnum.APR.toString(), Apr);
        Amount amount5 = new Amount(MonthEnum.MAY.toString(), May);
        Amount amount6 = new Amount(MonthEnum.JUN.toString(), Jun);
        Amount amount7 = new Amount(MonthEnum.JUL.toString(), Jul);
        Amount amount8 = new Amount(MonthEnum.AUG.toString(), Aug);
        Amount amount9 = new Amount(MonthEnum.SEPT.toString(), Sept);
        Amount amount10 = new Amount(MonthEnum.OCT.toString(), Oct);
        Amount amount11 = new Amount(MonthEnum.NOV.toString(), Nov);
        Amount amount12 = new Amount(MonthEnum.DEC.toString(), Dec);

        Amount[] year = {amount1,amount2,amount3,amount4,amount5,amount6,amount7,amount8,amount9,amount10,amount11,amount12};
        return year;
    }

    private CompareResult queryUserInfoDate(Date startTime, Date endTime) {
//        Date startTime = new Date(sd);
//        Date endTime = new Date(ed);

       /* QueryWrapper<UserInfo> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.ge("created",startTime);
        queryWrapper1.lt("created",endTime);
        List<UserInfo> userInfoList = userInfoMapper.selectList(queryWrapper1);*/
        List<UserInfo> userInfoList = queryUserInfoByTime(startTime,endTime);
        Amount[] thisYear = totalNewUserMonth(userInfoList);

        CompareResult compareResult = new CompareResult();
        compareResult.setThisYear(thisYear);


        DateTime startTimeLastYear = DateUtil.offsetMonth(startTime, -12);
        DateTime endTimeLastYear = DateUtil.offsetMonth(endTime, -12);

        /*QueryWrapper<UserInfo> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.ge("created",startTimeLastYear);
        queryWrapper2.lt("created",endTimeLastYear);
        List<UserInfo> userInfoList2 = userInfoMapper.selectList(queryWrapper2);*/
        List<UserInfo> userInfoList2 = queryUserInfoByTime(startTimeLastYear, endTimeLastYear);
        Amount[] lastYear = totalNewUserMonth(userInfoList2);
        compareResult.setLastYear(lastYear);
        return compareResult;
    }

    public Amount[] totalNewUserMonth(List<UserInfo> userInfoList){
        Integer Jan = 0;
        Integer Feb = 0;
        Integer Mar = 0;
        Integer Apr = 0;
        Integer May = 0;
        Integer Jun = 0;
        Integer Jul = 0;
        Integer Aug = 0;
        Integer Sept = 0;
        Integer Oct = 0;
        Integer Nov = 0;
        Integer Dec = 0;

        for (UserInfo userInfo : userInfoList) {
            Date created = userInfo.getCreated();
            int month = DateUtil.month(created);
            if (month== MonthEnum.JAN.getValue()){
                Jan++;
            } else if (month==MonthEnum.FEB.getValue()) {
                Feb++;
            }else if (month==MonthEnum.MAR.getValue()) {
                Mar++;
            }else if (month==MonthEnum.APR.getValue()) {
                Apr++;
            }else if (month==MonthEnum.MAY.getValue()) {
                May++;
            }else if (month==MonthEnum.JUN.getValue()) {
                Jun++;
            }else if (month==MonthEnum.JUL.getValue()) {
                Jul++;
            }else if (month==MonthEnum.AUG.getValue()) {
                Aug++;
            }else if (month==MonthEnum.SEPT.getValue()) {
                Sept++;
            }else if (month==MonthEnum.OCT.getValue()) {
                Oct++;
            }else if (month==MonthEnum.NOV.getValue()) {
                Nov++;
            }else if (month==MonthEnum.DEC.getValue()) {
                Dec++;
            }
        }
        Amount amount1 = new Amount(MonthEnum.JAN.toString(), Jan);
        Amount amount2 = new Amount(MonthEnum.FEB.toString(), Feb);
        Amount amount3 = new Amount(MonthEnum.MAR.toString(), Mar);
        Amount amount4 = new Amount(MonthEnum.APR.toString(), Apr);
        Amount amount5 = new Amount(MonthEnum.MAY.toString(), May);
        Amount amount6 = new Amount(MonthEnum.JUN.toString(), Jun);
        Amount amount7 = new Amount(MonthEnum.JUL.toString(), Jul);
        Amount amount8 = new Amount(MonthEnum.AUG.toString(), Aug);
        Amount amount9 = new Amount(MonthEnum.SEPT.toString(), Sept);
        Amount amount10 = new Amount(MonthEnum.OCT.toString(), Oct);
        Amount amount11 = new Amount(MonthEnum.NOV.toString(), Nov);
        Amount amount12 = new Amount(MonthEnum.DEC.toString(), Dec);

        Amount[] year = {amount1,amount2,amount3,amount4,amount5,amount6,amount7,amount8,amount9,amount10,amount11,amount12};
        return year;
    }


    public TotalDataVo queryTotal() {
        //累计用户(1)
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        Integer cumulativeUsers = userInfoMapper.selectCount(queryWrapper);

        //过去30天活跃用户(2)
        Date nowDate = new Date(System.currentTimeMillis());
        DateTime passMonthDate = DateUtil.offsetDay(nowDate, -30);
        Query query = Query.query(Criteria.where("logTime").gte(Convert.toInt(passMonthDate.getTime())));
        List<Log> logs = mongoTemplate.find(query, Log.class);

        List<Log> logs2 = new ArrayList<>();
        for (Log log : logs) {
            if (!CollUtil.contains(logs2,log.getUserId())){
                logs2.add(log);
            }
        }
        Integer activePassMonth = logs2.size();

        //过去7天活跃用户(3)
        DateTime passWeekDate = DateUtil.offsetDay(nowDate, -7);
        Query query2 = Query.query(Criteria.where("created").gte(1564735463000L));  // TODO gte(passWeekDate.getTime())
        List<Log> logs3 = mongoTemplate.find(query2, Log.class);
        List<Object> userIds = CollUtil.getFieldValues(logs3, "userId");

        QueryWrapper<UserInfo> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.in("user_id",userIds);
        Integer activePassWeek = userInfoService.queryUserCount(queryWrapper2);

        //今日新增用户(4)
        DateTime nowDateTime = new DateTime(nowDate);
        Integer newUsersToday = this.newUsercount(nowDateTime);

        //昨日新增用户
        DateTime passDay = DateUtil.offsetDay(nowDate, -1);
        Integer newUserYesteday = this.newUsercount(passDay);

        //今日新增用户涨跌率(5)
        Integer newUsersTodayRate = this.getRate(newUserYesteday,newUsersToday);

        //今日活跃用户涨跌率，单位百分数，正数为涨，负数为跌(公式: 今日用户数-昨日用户数/今日用户数*100%)
        //昨日活跃用户数(6)
        DateTime yesterday = DateUtil.yesterday();
        Integer activeUsersYesterday =this.activeUsercount(yesterday);

        //今日活跃用户数(7)
        Integer activeUsersToday = this.activeUsercount(nowDateTime);
        //今日活跃用户涨跌率(8)
        Integer activeUsersTodayRate = getRate(activeUsersYesterday,activeUsersToday);

        //前天活跃用户数
        DateTime beforeday = DateUtil.offsetDay(nowDate, -2);
        Integer activeBeforeDay = this.activeUsercount(beforeday);
        //昨日活跃用户涨跌率(9)
        Integer activeUsersYesterdayRate = this.getRate(activeBeforeDay,activeUsersYesterday);

        //今日登录次数(10)
        Integer loginTimesToday = this.loginTimes(nowDateTime);
        //昨日登录次数
        Integer loginTimesYesterday = loginTimes(yesterday);
        //今日登录次数涨跌率(11)
        Integer loginTimesTodayRate = getRate(loginTimesToday,loginTimesYesterday);

        //过去7天平均日使用时长，单位秒
        DateTime sevendayPass = DateUtil.offsetDay(nowDate, -7);
        Query query3 = Query.query(Criteria.where("created").gte(sevendayPass));
        List<Log> logList2 = mongoService.queryLogList(query3);

        //登录时长集合
        List<Long> totalTimeList = new ArrayList<>();
        for (Log log : logList2) {
            Long loginTime = log.getLogOutTime() - log.getLogTime();
            totalTimeList.add(loginTime);
        }
        Long totalTime = 0L;  //过去7天总共的登录时长
        for (Long time : totalTimeList) {
            totalTime += time;
        }
        List<Object> userIdList = CollUtil.getFieldValues(logList2, "userId");
        List<com.tanhua.bg.pojo.UserInfo> userInfoList = userInfoService.queryUserInfoByUserIdList(userIdList);
        Long useTimePassWeek = 0L;
        if (CollUtil.isNotEmpty(userInfoList)){
          useTimePassWeek = totalTime/userInfoList.size();//(12)
        }


        TotalDataVo totalDataVo = new TotalDataVo();
        totalDataVo.setCumulativeUsers(cumulativeUsers);
        totalDataVo.setActivePassMonth(activePassMonth);
        totalDataVo.setActivePassWeek(activePassWeek);
        totalDataVo.setNewUsersToday(newUsersToday);
        totalDataVo.setNewUsersTodayRate(newUsersTodayRate);
        totalDataVo.setLoginTimesToday(loginTimesToday);
        totalDataVo.setLoginTimesTodayRate(loginTimesTodayRate);
        totalDataVo.setActiveUsersToday(activeUsersToday);
        totalDataVo.setActiveUsersTodayRate(activeUsersTodayRate);
        totalDataVo.setUseTimePassWeek(useTimePassWeek);
        totalDataVo.setActiveUsersYesterday(activeUsersYesterday);
        totalDataVo.setActiveUsersYesterdayRate(activeUsersYesterdayRate);

        return totalDataVo;
    }

    //计算涨跌率
    private Integer getRate(Integer beforeday, Integer today) {
        if (beforeday==0||today==0){
            return null;
        }
        return (today - beforeday)/beforeday;
    }


    //查询日新增用户数
    private Integer newUsercount(DateTime dateTime){
        //今日新增用户
        DateTime beginOfDay = DateUtil.beginOfDay(dateTime);
        DateTime endOfDay = DateUtil.endOfDay(dateTime);

        QueryWrapper<UserInfo> queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.ge("created",beginOfDay);
        queryWrapper3.le("created",endOfDay);
        return userInfoService.queryUserCount(queryWrapper3);
    }

    //查询日活跃用户数
    private Integer activeUsercount(DateTime dateTime){
        DateTime todayBegin = DateUtil.beginOfDay(dateTime);
        DateTime todayEnd = DateUtil.endOfDay(dateTime);
        Query query = Query.query(Criteria.where("logTime").gte(todayBegin)
                .andOperator(Criteria.where("logTime").lte(todayEnd)));

        List<Log> logList = mongoService.queryLogList(query);
        List<Object> userIdList = CollUtil.getFieldValues(logList, "userId");
        if (CollUtil.isEmpty(userIdList)){
            return 0;
        }
        List<com.tanhua.bg.pojo.UserInfo> userInfoList = userInfoService.queryUserInfoByUserIdList(userIdList);
        return userInfoList.size();
    }

    //查询日登录次数
    private Integer loginTimes(DateTime dateTime){
        DateTime beginOfDay = DateUtil.beginOfDay(dateTime);
        DateTime endOfDay = DateUtil.endOfDay(dateTime);
        List<Log> logsList = queryLogsByTime(beginOfDay, endOfDay);
        return logsList.size();
    }
}
